<template>
    <div class="layout">
        <Row type="flex" class="body-container">
            <Col :span="5" class="layout-menu-left">
            <Menu active-name="1" theme="dark" width="auto">
                <div class="layout-logo-left"></div>
                <MenuItem name="1">
                <Icon type="ios-cloud" :size="14"></Icon>
                <span class="layout-text">云管理</span>
                </MenuItem>
                <MenuItem name="2">
                <Icon type="ios-gear" :size="14" @click="$router.push('/upload')"></Icon>
                <span class="layout-text">设置</span>
                </MenuItem>
            </Menu>
            </Col>
            <Col :span="19">
            <div class="layout-header">
                <div class="left">
                    <!-- <search></search> -->
                </div>
                <div class="right">
                    <Button type="text" class="cloud-upload" @click="toggleUploadTask(true)">
                        <Icon type="ios-cloud-upload" size="32"></Icon>
                    </Button>
                </div>
            </div>
            <div class="layout-breadcrumb">
                <Breadcrumb>
                    <BreadcrumbItem v-for="(item,key) in path" :key="key">
                        <span @click="changePath(key)" :style="{cursor: path.length - 1 != key ? 'pointer' : ''}">
                            {{ item.pathname }}
                        </span>
                    </BreadcrumbItem>
                </Breadcrumb>
            </div>
            <div class="layout-content">
                <div class="layout-content-main" v-select-box="{selectCallback}">
                    <Table border :columns="columns" :data="data" :height="440" @on-selection-change="selectFile"></Table>
                </div>
            </div>
            <div class="layout-button">
                <Page :total="dataTotal" :page-size="50" @on-change="changePage" show-total></Page>
                <div class="func-botton">
                    <Button type="info" @click="refreshPath">刷新</Button>
                    <Button type="error" :disabled="selectedList.length ? false: true" @click="deteleSelectedFile">删除选中文件</Button>
                </div>
            </div>
            </Col>
        </Row>
        <!-- 上传组件 -->
        <Upload-Task :showUploadTask="showUploadTask" @toggleUploadTask="toggleUploadTask" @refreshPath="refreshPath"></Upload-Task>
    </div>
</template>

<script>
import electron from 'electron';
import { ipcRenderer } from 'electron';
const fs = require("fs");
const path = require("path");
const dataPath = require("electron").remote.app.getPath('userData');

const fileUrl = path.join(dataPath, 'fileCache.json');


let fileCache;
if (fs.existsSync(fileUrl)) {
  fileCache = JSON.parse(fs.readFileSync(fileUrl));
} else {
  fileCache = {};
  fs.writeFileSync(fileUrl, '{}');
}

import vlcCommand from '../../vlc';

export default {
  name: 'admin',
  components: {
    // 上传任务组件
    "Upload-Task": require('../upload').default,
    "search": require('../search/index.vue').default
  },
  data() {
    return {
      // 上传任务列表
      showUploadTask: false,
      // 当前目录文件列表
      data: [],
      // 当前目录文件总数
      dataTotal: 0,
      // 选中的文件列表
      selectedList: [],
      // 图片列表
      pictrues: [],
      // 目录路径
      path: [{ pathname: '根目录', id: '0' }],
      // table配置
      columns: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '文件名',
          key: 'name',
          render: (h, params) => {
            // 为文件的情况下, 绑定查看文件事件，展示文件信息。 
            // 为目录的情况下，绑定浏览文件夹事件
            return h('div', {
              on: {
                click: () => {
                  if (params.row.isFixedDir) {
                    this.goFolder(params.row)
                  }
                }
              },
              style: {
                cursor: params.row.isFixedDir ? 'pointer' : ''
              }
            }, [
                h('Icon', {
                  props: {
                    type: params.row.contentType && params.row.contentType['0'] == 1 ? 'image' :
                      params.row.contentType && params.row.contentType['0'] == 2 ? 'ios-musical-notes' :
                        params.row.contentType && params.row.contentType['0'] == 3 ? 'social-youtube' :
                          params.row.contentType && ['0', '4', '5', '6', '7', '8'].includes(params.row.contentType['0']) ? 'document-text' : 'ios-folder',
                    color: params.row.contentType && params.row.contentType['0'] == 1 ? '#f90' :
                      params.row.contentType && params.row.contentType['0'] == 2 ? 'rgb(53,132,225)' :
                        params.row.contentType && params.row.contentType['0'] == 3 ? '#fe6428' :
                          params.row.contentType && ['0', '4', '5', '6', '7', '8'].includes(params.row.contentType['0']) ? 'rgb(106,138,177)' : 'rgb(253,198,6)',
                  },
                  style: {
                    marginRight: '10px'
                  }
                }),
                h(params.row.isFixedDir ? 'strong' : 'span', params.row.isFixedDir ? params.row.catalogName['0'] : params.row.contentName['0'])
              ]);
          }
        },
        {// 新增文件md5显示
          title: 'MD5',
          key: 'md5',
          width: 270,
          render: (h, parms) => {
            return h('span', parms.row.digest ? parms.row.digest[0] : '');
          }
        },
        {
          title: '大小',
          key: 'size',
          width: 100,
          render: (h, parms) => {
            return h('span', this.getFilesize(parms.row.contentSize))
          }
        },
        {
          title: '操作',
          key: 'action',
          width: 150,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'primary',
                  size: 'small',
                  disabled:
                    // 如果类型是图片、视频类型或者后缀是视频格式的文件
                    (params.row.contentType && ['1', '3'].includes(params.row.contentType[0])) ||
                      (params.row.contentName && ['mp4', 'mpeg', 'avi', 'mov', 'wmv', '3gp', 'mkv', 'flv', 'f4v', 'rmvb', 'webm', 'qsv'].includes(params.row.contentName[0].substring(params.row.contentName[0].lastIndexOf('.') + 1).toLocaleLowerCase()))
                      ? false : true,
                },
                class: {
                  'preview-img': params.row.contentType && params.row.contentType[0] == '1' ? true : false
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: (e) => {
                    if (params.row.contentType && params.row.contentType[0] === '1') {
                      // 图片预览
                      if (this.pictrues.length) {
                        this.$preview.open(params.row['PicIndex'], this.pictrues, {});
                      }
                    } else if ((params.row.contentType && params.row.contentType[0] === '3') || (params.row.contentName && ['mp4', 'mpeg', 'avi', 'mov', 'wmv', '3gp', 'mkv', 'flv', 'f4v', 'rmvb', 'webm', 'qsv'].includes(params.row.contentName[0].substring(params.row.contentName[0].lastIndexOf('.') + 1).toLocaleLowerCase()))) {
                      // 视频预览
                      vlcCommand.kill();
                      vlcCommand.checkInstall(null, (err, pathUrl) => {
                        if (err) return electron.shell.openExternal('http://www.videolan.org/vlc/');
                        ipcRenderer.send('get-download', {
                          access_token: this.access_token,
                          fileid: params.row.contentID[0],
                          phone: params.row.owner[0]
                        });
                        ipcRenderer.once('download-back', (event, data) => {
                          vlcCommand.spawn(pathUrl, data.result.String[0])
                        });
                      });
                    }
                  }
                }
              }, '预览'),
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small',
                  disabled: params.row.contentType ? false : true
                },
                on: {
                  click: () => {
                    this.deleteFile(params.row);
                  }
                }
              }, '删除')
            ]);
          }
        }
      ],
    }
  },
  watch: {
    // 观察当前路径， 提供上传路径
    path() {
      if (this.path.length == 1) {
        this.$store.commit('SAVE_FOLDERID', fileCache.mydiskID);
      } else if (this.path.length > 1) {
        this.$store.commit('SAVE_FOLDERID', this.path[this.path.length - 1].id);
      }
    }
  },
  computed: {
    access_token() {
      return this.$store.getters.GET_ACCESSTOKEN;
    },
    iconSize() {
      return this.spanLeft === 5 ? 14 : 24;
    }
  },
  created() {
    this.$Spin.show();
    ipcRenderer.send('get-list', { access_token: this.access_token });
    ipcRenderer.once('list-back', (event, data, mydiskID) => {
      if (mydiskID) {
        this.$store.commit('SAVE_FOLDERID', mydiskID);
        fileCache.mydiskID = mydiskID;
        fs.writeFileSync(fileUrl, JSON.stringify(fileCache));
      }
      // 统一处理得到的数据
      this.processData(data);
      this.$Spin.hide();
    })
  },
  methods: {
    selectCallback(isselect) {
      console.log(isselect);
    },
    // 勾选事件
    selectFile(selectedList) {
      this.selectedList = selectedList;
    },
    // 切换上传任务显示
    toggleUploadTask(bol) {
      this.showUploadTask = bol;
    },
    // 统一处理获取到的列表信息
    processData(data) {
      if (data.errmsg || data.code == 1) {
        if (data.errmsg && data.errmsg.status === 401) {
          // 失去权限重新获取权限
          this.$emit('refresh-token');
        } else {
          this.$Message.error(data.errmsg);
        }
        this.$Spin.hide();
        return;
      }
      this.dataTotal = Number(data.result.getDiskResult["0"].nodeCount["0"]);
      let catalogList = [];
      let contentList = [];
      if (data.result.getDiskResult["0"].catalogList) {
        catalogList = data.result.getDiskResult["0"].catalogList["0"].catalogInfo;
        catalogList.map((item) => {
          item['_disabled'] = true;
        })
      }
      if (data.result.getDiskResult["0"].contentList) {
        contentList = data.result.getDiskResult["0"].contentList["0"].contentInfo;
        let index = 0;
        this.pictrues = [];
        contentList.map((item) => {
          // 如果是图片类型，为图片预览做准备
          if (item.contentType[0] == '1') {
            this.pictrues.push({
              src: item.bigthumbnailURL[0].replace('http://download.caiyun.feixin.10086.cn:80', 'https://download.caiyun.feixin.10086.cn'),
              w: 0,
              h: 0
            });
            item['PicIndex'] = index;
            index++;
          }
        })
      }
      this.data = [...catalogList, ...contentList];
    },
    // 分页
    changePage(page) {
      this.$Spin.show();
      let id = this.path[this.path.length - 1].id;
      ipcRenderer.send('get-list', {
        access_token: this.access_token,
        folderid: id !== '0' ? id : '',
        startNumber: 50 * (page - 1) + 1,
        endNumber: 50 * page
      });
      ipcRenderer.once('list-back', (event, data) => {
        this.processData(data);
        this.$Spin.hide();
      });
    },
    // 刷新当前页
    refreshPath() {
      this.$Spin.show();
      let id = this.path[this.path.length - 1].id;
      ipcRenderer.send('get-list', { access_token: this.access_token, folderid: id !== '0' ? id : '' });
      ipcRenderer.once('list-back', (event, data) => {
        this.processData(data);
        this.$Spin.hide();
      });
    },
    // 浏览文件夹
    goFolder(item) {
      this.$Spin.show();
      ipcRenderer.send('get-list', { access_token: this.access_token, folderid: item.catalogID[0] });
      ipcRenderer.once('list-back', (event, data) => {
        this.processData(data);
        this.path.push({
          pathname: item.catalogName[0],
          id: item.catalogID[0]
        });
        this.$Spin.hide();
      });
    },
    // 导航栏改变目录
    changePath(key) {
      if (this.path.length - 1 != key) {
        this.$Spin.show();
        ipcRenderer.send('get-list', { access_token: this.access_token, folderid: this.path[key].id !== '0' ? this.path[key].id : '' });
        ipcRenderer.once('list-back', (event, data) => {
          this.processData(data);
          this.$Spin.hide();
          this.path.splice(key + 1);
        });
      }
    },
    // 删除文件
    deleteFile(item) {
      let _this = this;
      this.$Modal.confirm({
        title: '提示',
        content: '确定要删除该文件吗？',
        onOk() {
          this.$Spin.show();
          ipcRenderer.send('delete-file', { access_token: _this.access_token, filelist: [item.contentID[0]] });
          ipcRenderer.once('delete-back', (event, data) => {
            if (data.result.$.resultCode == '0') {
              _this.$Message.success('删除成功！');
              setTimeout(() => {
                _this.refreshPath();
              }, 500)
            } else {
              _this.$Spin.hide();
              _this.$Message.error('删除失败！');
            }
          });
        }
      });
    },
    // 删除文件列表
    deteleSelectedFile() {
      let _this = this;
      if (!this.selectedList.length) return;
      this.$Modal.confirm({
        title: '提示',
        content: '确定要删除选中的文件吗？',
        onOk() {
          _this.$Spin.show();
          let list = [];
          _this.selectedList.map((item) => {
            list.push(item.contentID[0]);
          });
          ipcRenderer.send('delete-file', { access_token: _this.access_token, filelist: list });
          ipcRenderer.once('delete-back', (event, data) => {
            if (data.result.$.resultCode == '0') {
              _this.$Message.success('删除成功！');
              setTimeout(() => {
                _this.refreshPath();
              }, 500)
            } else {
              _this.$Spin.hide();
              _this.$Message.error('删除失败！');
            }
          });
        }
      });
    },
    // 转换文件大小
    getFilesize(filesize) {
      if (!filesize) return '/';
      let tempsize = Number(filesize[0]);
      if (!Number.isInteger(tempsize)) return '/';
      let unitArr = new Array("Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB");
      let index = 0;
      let srcsize = parseFloat(tempsize);
      index = Math.floor(Math.log(srcsize) / Math.log(1024));
      let size = srcsize / Math.pow(1024, index);
      size = size.toFixed(2);//保留的小数位数
      return size + unitArr[index];
    },
  }
}
</script>

<style scoped>
@import url(./index.css);
</style>
